package com.android.manghe.common.webview;

import android.app.Activity;
import android.content.Intent;
import android.webkit.JavascriptInterface;

import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.WebViewUserInfo;
import com.android.manghe.main.MainActivity;
import com.android.manghe.mine.model.UserRes;
import com.android.manghe.user.activity.LoginActivity;
import com.google.gson.Gson;

/**
 * JS访问Java的类
 *
 * @author ZhangWeijun
 * @time 2018/6/5 9:18
 */
public class JsInteraction {

    private WebViewEventListener webViewEventListener;
    private Activity context;

    public JsInteraction(Activity context, WebViewEventListener listener) {
        this.context = context;
        this.webViewEventListener = listener;
    }

    public void setListener(WebViewEventListener webViewEventListener) {
        this.webViewEventListener = webViewEventListener;
    }

    /**
     * js调用方法
     */
    @JavascriptInterface
    public String getLoginMsg() {
        UserRes.UserInfo userInfo = UserHolder.getUserInfo(context);
        if (userInfo == null) {
            ((Activity) context).finish();
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return null;
        } else {
            String jsonUser = new Gson().toJson(new WebViewUserInfo(userInfo.TOKEN, userInfo.UID, userInfo.UNAME, userInfo.avatar));
            return jsonUser;
        }
    }

    @JavascriptInterface
    public void goToLogin() {
        if (webViewEventListener != null) {
            webViewEventListener.goToLogin();
        }
    }

    @JavascriptInterface
    public void check_balance() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("isToChangeTab", true);
        intent.putExtra("position", 4);
        context.startActivity(intent);
        context.finish();
    }

    @JavascriptInterface
    public void open_Box() {
        context.finish();
    }
}
